#!/bin/bash

###############################################
# Kafka Server 配置文件
###############################################
# KAFKA_SERVER_PROFILE

###############################################
# Zookeeper 配置
###############################################
## zookeeper 地址   zookeeper.connect=localhost:2181
# ZOOKEEPER
#
## zookeeper 超时时间   zookeeper.connection.timeout.ms=18000
# ZOOKEEPER_TIMEOUT_MS

###############################################
# Kafka 其他配置
###############################################
## 监听配置 listeners=PLAINTEXT://:9092
# SERVER_LISTENERS
## 分区配置 num.partitions=1 
# PARTITIONS_NUM
## 日志保存时长 log.retention.hours=168
# LOG_RETENTION_HOURS

DEF_PROFILE=config/server.properties

function check_env(){
    echo "check env !!!!!!!!!!!!!!!!!!!!!!!!!"

    # zookeeper.connect=localhost:2181
    if [ "$ZOOKEEPER" = "" ]; then
        export ZOOKEEPER=localhost:2181
    fi

    # zookeeper.connection.timeout.ms=18000
    if [ "$ZOOKEEPER_TIMEOUT_MS" = "" ]; then
        export ZOOKEEPER_TIMEOUT_MS=18000
    fi

    # listeners=PLAINTEXT://:9092
    if [ "$SERVER_LISTENERS" = "" ]; then
        export SERVER_LISTENERS=PLAINTEXT://:9092
    fi

    # num.partitions=1
    if [ "$PARTITIONS_NUM" = "" ]; then
        export PARTITIONS_NUM=1
    fi

    # log.retention.hours=168
    if [ "$LOG_RETENTION_HOURS" = "" ]; then
        export LOG_RETENTION_HOURS=168
    fi

    sed -i -e "s|^\(#\s\)\?zookeeper\.connect=.*$|zookeeper\.connect=$ZOOKEEPER|g" $DEF_PROFILE
    sed -i -e "s|^\(#\s\)\?zookeeper\.connection\.timeout\.ms=.*$|zookeeper\.connection\.timeout\.ms=$ZOOKEEPER_TIMEOUT_MS|g" $DEF_PROFILE
    sed -i -e "s|^\(#\s\)\?listeners=.*$|listeners=$SERVER_LISTENERS|g" $DEF_PROFILE
    sed -i -e "s|^\(#\s\)\?num\.partitions=.*$|num\.partitions=$PARTITIONS_NUM|g" $DEF_PROFILE
    sed -i -e "s|^\(#\s\)\?log\.retention\.hours=.*$|log\.retention\.hours=$LOG_RETENTION_HOURS|g" $DEF_PROFILE
}

if [ "$KAFKA_SERVER_PROFILE" = "" ]; then
    check_env
    export KAFKA_SERVER_PROFILE=$DEF_PROFILE
fi

RUN_DIR=`pwd`
cd $RUN_DIR
unset $RUN_DIR

echo "$@"

# cat $KAFKA_SERVER_PROFILE

# exec "$@ $KAFKA_SERVER_PROFILE" 
bin/kafka-server-start.sh $KAFKA_SERVER_PROFILE